<template>
<view class="content">
   <button type="default" @click="selectImg">选择文件上传</button>
   <image v-if="fileUrl" class="image" :src="fileUrl"></image>
</view>
</template>

<script>
import { ossImage } from '../../utils/upload';
export default {
   data() {
      return {
         title: 'Hello',
         fileUrl: ''
      };
   },
   onLoad() {

   },
   methods: {
	  selectAvatar() {
		  var that = this;
		  	var timestamp = Date.parse(new Date());
		  	var date = new Date(timestamp);
		  	var Y = date.getFullYear(); //年
		  	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1); //月
		  	var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); //日
		  	var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(); //时
		  	var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(); //分
		  	var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(); //秒
		
		  uni.chooseImage({
			  success: (chooseImageRes) => {
			  	var file = chooseImageRes.tempFiles[0];
			  	if (!file) return;
			  	// 获取要上传的本地文件路径
			  	var tempFilePath  = chooseImageRes.tempFilePaths[0];
			  	// 获取上传的文件后缀，然后后端生成随机 COS 路径地址
			  	var lastIndex = tempFilePath .lastIndexOf('.');
			  	var extName = lastIndex > -1 ? tempFilePath .slice(lastIndex + 1) : '';
				var filePath = Y + '_' + M + '_' + D + '_uni/' + Y + '-' + M + '-' + D + '_' + h + ':' + m + ':' + s + '_'+ '.' + extName;
				console.log(filePath)

				uni.uploadFile({
					url: 'https://up-z2.qiniup.com',  //华南区
					filePath: tempFilePath,
					name: 'file',
					formData: {
						'key': filePath,
						'token': 'CgYxgFuRARB6c4pRui6Jpc31yA6tCaQW-IGkCB6Z:iJlLbZqrr-QRQ_mg3aEaWX6t4u8=:eyJzY29wZSI6InNwaW5hY2hlYWQiLCJkZWFkbGluZSI6MTcxODI2Mjg5OX0='
					},
					success: (res) => {
						console.log('上传结果', res)
						if (res.statusCode == 200) {
							let result = JSON.parse(res.data)
						}else{
							console.log("上传失败")
						}
					},
					fail: (err) => {
						console.log("请求失败", err)
					}
				})
			  }
		  })
	  },
	  selectImg() {
		  uni.chooseImage({
		  	success: (chooseImageRes) => {
				var file = chooseImageRes.tempFiles[0];
				if (!file) return;
				// 获取要上传的本地文件路径
				var tempFilePath  = chooseImageRes.tempFilePaths[0];
				// 获取上传的文件后缀，然后后端生成随机 COS 路径地址
				var lastIndex = tempFilePath .lastIndexOf('.');
				var extName = lastIndex > -1 ? tempFilePath .slice(lastIndex + 1) : '';
		  		ossImage(extName, tempFilePath).then(res => {
					console.log("上传成功", res)
				}).then(err => {
					console.log("上传失败", err)
				})
		  	}
		  })
	  }
   }
}
</script>

<style>
.content {
   padding: 20px 0;
   display: flex;
   flex-direction: column;
   align-items: center;
   justify-content: center;
}

.image {
   margin-top: 20px;
   margin-left: auto;
   margin-right: auto;
}
</style>